/*
** expulse.c for zappy in /home/guidet_m/TECK2/projets/zappy/server_zappy
** 
** Made by michael guidet
** Login   <guidet_m@epitech.net>
** 
** Started on  Mon Jul  4 15:38:10 2011 michael guidet
** Last update Mon Jul 11 10:14:42 2011 michael guidet
*/

#include "server.h"

void	action_expulse_move(t_fd *fd, t_env *e, int expulseur)
{
  char		cmd2[BUF_SIZE];
  t_player_list	*tmp;
  int		victime;
  int		k;

  for (tmp = e->map[fd->pl->y][fd->pl->x].players; tmp; tmp = tmp->next)
    {
      if (fd->pl != tmp->drone)
	remove_drone_from_case(e->map, fd->pl->x, fd->pl->y, fd->pl);
      victime = fd->pl->look_at;
      if (fd->pl->look_at == NORD || fd->pl->look_at == SUD)
	tmp->drone->y += ((fd->pl->look_at == NORD) ? (-1) : (1));
      else if (fd->pl->look_at == EST ||
	       fd->pl->look_at == OUEST)
	tmp->drone->x += ((fd->pl->look_at == EST) ? (1) : (-1));
      fd->pl->x = ((fd->pl->x < 0) ? (e->width - 1) :
		      (fd->pl->x >= e->width) ? (0) : fd->pl->x);
      fd->pl->y = ((fd->pl->y < 0) ? (e->height - 1) :
		      (fd->pl->y >= e->height) ? (0) : fd->pl->y);
      add_drone_to_case(e->map, tmp->drone->x, tmp->drone->y, tmp->drone);
      k = action_expulse_place(expulseur, victime);
      sprintf(cmd2, "deplacement %d\n", k);
      add_string_to_list(&fd->send_list, cmd2);
    }
}

void	action_expulse(t_fd *fd, t_env *e, char *cmd)
{
  t_player_list	*tmp;
  t_fd		*tp;
  int		expulseur;
  char		cmd2[BUF_SIZE];

  printf("%sDrone %d %s Execute %s%s\n", PURPLE, fd->pl->id,
	 fd->pl->team, cmd, DEFAUT);
  fd->wait = -1;
  fd->idaction = -1;
  expulseur = fd->pl->look_at;
  action_expulse_move(fd, e, expulseur);
  sprintf(cmd2, "pex %d\n", fd->pl->id);
  for (tmp = e->map[fd->pl->y][fd->pl->x].players; tmp; tmp = tmp->next)
    {
      if (tmp->drone != fd->pl)
	sprintf(cmd2, "%sppo %d %d %d %d\n", cmd2, tmp->drone->id,
                   tmp->drone->x, tmp->drone->y, tmp->drone->y);
    }
  for (tp = e->fd; tp; tp = tp->next)
    if (tp->type == GRAPH)
      add_string_to_list(&tp->send_list, cmd2);
  add_string_to_list(&fd->send_list, "ok\n");
}

int	action_expulse_place(int expulseur, int victime)
{
  if (victime == NORD)
    return ((expulseur + 3) % 8 + 1);
  else if (victime == OUEST)
    return ((expulseur + 1) % 8 + 1);
  else if (victime == SUD)
    return (expulseur);
  return ((expulseur + 5) % 8 + 1);
}
